package com.heng.atomics;

import javax.jws.Oneway;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

class MyNumber{
    AtomicInteger atomicInteger = new AtomicInteger();

    public void addPlusPlus(){
        int andIncrement = atomicInteger.getAndIncrement();

    }
}


public class OverAtomicIntegerDemo1 {
    public static final int SIZE = 50;

    public static void main(String[] args) throws InterruptedException {
        MyNumber myNumber = new MyNumber();
        CountDownLatch countDownLatch = new CountDownLatch(SIZE);
        for (int i = 1;i<=SIZE;i++) {
            new Thread(()->{
                try{
                    for (int j = 0; j < 1000; j++) {
                        myNumber.addPlusPlus();
                    }
                }finally {
                    countDownLatch.countDown();
                }
            },String.valueOf(i)).start();
        }
        //try {TimeUnit.SECONDS.sleep(5);}catch (InterruptedException e) {e.printStackTrace();}
        //休息一段时间，等上面的线程都执行完成后，才能输出正确的结果！
        //否则的到的结果不是执行完成后的结果！
        // 上面的停顿5秒时不合理的！
        countDownLatch.await();//解决等5秒的问题
        System.out.println(Thread.currentThread().getName()+"\t result: " + myNumber.atomicInteger.get());
    }
}
